// import React, { useState, useEffect, useRef } from 'react';
// import { QuestionCircleOutlined, SyncOutlined, CustomerServiceOutlined, RedditOutlined, SmileOutlined } from '@ant-design/icons';
// import { FloatButton } from 'antd';
// import { EmojiClickData } from 'emoji-picker-react';
// import EmojiPicker from 'emoji-picker-react'; // Ensure the correct import for EmojiPicker
// import './index.css';

// interface Message {
//     id: number;
//     text: string;
//     sender: 'user' | 'bot';
//     imageUrl?: string; // Optional image URL for messages with images
// }

// const Index: React.FC = () => {
//     const [isVisible, setIsVisible] = useState<boolean>(false);
//     const [messages, setMessages] = useState<Message[]>([]);
//     const [inputValue, setInputValue] = useState<string>('');
//     const [showEmojiPicker, setShowEmojiPicker] = useState<boolean>(false);
//     const [image, setImage] = useState<File | null>(null);
//     const [imagePreview, setImagePreview] = useState<string | null>(null);
//     const messagesEndRef = useRef<HTMLDivElement>(null);

//     const toggleChatBox = () => setIsVisible(!isVisible);

//     const scrollToBottom = () => {
//         messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
//     };

//     useEffect(() => {
//         scrollToBottom();
//     }, [messages]);

//     const handleSendMessage = () => {
//         if (inputValue.trim() === '' && !image) return;

//         const newMessage: Message = {
//             id: messages.length + 1,
//             text: inputValue,
//             sender: 'user',
//             imageUrl: imagePreview || undefined,
//         };

//         setMessages((prevMessages) => [...prevMessages, newMessage]);
//         setInputValue('');
//         setImage(null);
//         setImagePreview(null);

//         // Simulate bot response
//         setTimeout(() => {
//             const botMessage: Message = {
//                 id: messages.length + 2,
//                 text: `Hi~我是创客贴机器人客服，可以输入问题向我提问哦~`,
//                 sender: 'bot',
//             };
//             setMessages((prevMessages) => [...prevMessages, botMessage]);
//         }, 1000);
//     };

//     const handleEmojiClick = (emojiData: EmojiClickData) => {
//         setInputValue((prev) => prev + emojiData.emoji);
//         setShowEmojiPicker(false);
//     };

//     const handleImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
//         const file = event.target.files?.[0];
//         if (file) {
//             setImage(file);
//             setImagePreview(URL.createObjectURL(file));
//         }
//     };

//     return (
//         <div>
//             <FloatButton.Group shape="square" style={{ insetInlineEnd: 26 }}>
//                 <FloatButton tooltip={<div>疑问</div>} icon={<QuestionCircleOutlined />} />
//                 <FloatButton onClick={toggleChatBox} tooltip={<div>客服</div>} icon={<CustomerServiceOutlined />} />
//                 <FloatButton tooltip={<div>刷新</div>} icon={<SyncOutlined />} />
//                 <FloatButton.BackTop visibilityHeight={0} tooltip={<div>回到顶部</div>} />
//             </FloatButton.Group>
//             {isVisible && (
//                 <div className="chat-box">
//                     <div className="chattop">
//                         <span><RedditOutlined /></span>
//                         <p>创客贴机器人客服小助手</p>
//                         <p onClick={toggleChatBox} className='jian'>—</p>
//                     </div>
//                     <div className="chatmain">
//                         {messages.map((message) => (
//                             <div
//                                 key={message.id}
//                                 style={{
//                                     textAlign: message.sender === 'user' ? 'right' : 'left',
//                                     marginBottom: '10px',
//                                 }}
//                             >
//                                 <div
//                                     style={{
//                                         display: 'inline-block',
//                                         padding: '5px 10px',
//                                         borderRadius: '5px',
//                                         backgroundColor: message.sender === 'user' ? '#007bff' : '#fff',
//                                         color: message.sender === 'user' ? '#fff' : '#000',
//                                     }}
//                                 >
//                                     {message.text}
//                                     {message.imageUrl && <img src={message.imageUrl} alt="uploaded" style={{ width: '100px', marginLeft: '10px' }} />}
//                                 </div>
//                             </div>
//                         ))}
//                         <div ref={messagesEndRef} />
//                     </div>
//                     <div className='chatfooter'>
//                         <div className='rengong'></div>
//                         <div className='inp'>
//                             <input
//                                 type="text"
//                                 value={inputValue}
//                                 onChange={(e) => setInputValue(e.target.value)}
//                                 placeholder='很高兴为您服务，请描述您的问题'
//                             />
//                             <button onClick={handleSendMessage}>发送</button>
//                             <SmileOutlined onClick={() => setShowEmojiPicker((prev) => !prev)} />
//                             {showEmojiPicker && (
//                                 <div style={{ position: 'absolute', bottom: '50px', right: '10px' }}>
//                                     <EmojiPicker onEmojiClick={handleEmojiClick} />
//                                 </div>
//                             )}
//                             <input type="file" accept="image/*" onChange={handleImageChange} style={{ marginLeft: '10px' }} />
//                             {imagePreview && <img src={imagePreview} alt="preview" style={{ width: '50px', marginLeft: '10px' }} />}
//                         </div>
//                     </div>
//                 </div>
//             )}
//         </div>
//     );
// }

// export default Index;

import React, { useState, useEffect, useRef } from 'react';
import { QuestionCircleOutlined, SyncOutlined, CustomerServiceOutlined, RedditOutlined, SmileOutlined } from '@ant-design/icons';
import { FloatButton, Modal } from 'antd';
import { EmojiClickData } from 'emoji-picker-react';
import EmojiPicker from 'emoji-picker-react';
import './index.css';

interface Message {
    id: number;
    text: string;
    sender: 'user' | 'bot';
    imageUrl?: string; // Optional image URL for messages with images
}

const Index: React.FC = () => {
    const [isVisible, setIsVisible] = useState<boolean>(false);
    const [messages, setMessages] = useState<Message[]>([]);
    const [inputValue, setInputValue] = useState<string>('');
    const [showEmojiPicker, setShowEmojiPicker] = useState<boolean>(false);
    const [image, setImage] = useState<File | null>(null);
    const [imagePreview, setImagePreview] = useState<string | null>(null);
    const [previewImageUrl, setPreviewImageUrl] = useState<string | null>(null); // State to manage preview image URL
    const messagesEndRef = useRef<HTMLDivElement>(null);

    const toggleChatBox = () => setIsVisible(!isVisible);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    const handleSendMessage = () => {
        if (inputValue.trim() === '' && !image) return;

        const newMessage: Message = {
            id: messages.length + 1,
            text: inputValue,
            sender: 'user',
            imageUrl: imagePreview || undefined,
        };

        setMessages((prevMessages) => [...prevMessages, newMessage]);
        setInputValue('');
        setImage(null);
        setImagePreview(null);

        // Simulate bot response
        setTimeout(() => {
            const botMessage: Message = {
                id: messages.length + 2,
                text: `Hi~我是创客贴机器人客服，可以输入问题向我提问哦~`,
                sender: 'bot',
            };
            setMessages((prevMessages) => [...prevMessages, botMessage]);
        }, 1000);
    };

    const handleEmojiClick = (emojiData: EmojiClickData) => {
        setInputValue((prev) => prev + emojiData.emoji);
        setShowEmojiPicker(false);
    };

    const handleImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (file) {
            setImage(file);
            setImagePreview(URL.createObjectURL(file));
        }
    };

    const handleImageClick = (url: string) => {
        setPreviewImageUrl(url); // Set the URL for the image to preview
    };

    const handleModalClose = () => {
        setPreviewImageUrl(null); // Close the modal by resetting the URL
    };

    return (
        <div>
            <FloatButton.Group shape="square" style={{ insetInlineEnd: 26 }}>
                <FloatButton tooltip={<div>疑问</div>} icon={<QuestionCircleOutlined />} />
                <FloatButton onClick={toggleChatBox} tooltip={<div>客服</div>} icon={<CustomerServiceOutlined />} />
                <FloatButton tooltip={<div>刷新</div>} icon={<SyncOutlined />} />
                <FloatButton.BackTop visibilityHeight={0} tooltip={<div>回到顶部</div>} />
            </FloatButton.Group>
            {isVisible && (
                <div className="chat-box">
                    <div className="chattop">
                        <span><RedditOutlined /></span>
                        <p>创客贴机器人客服小助手</p>
                        <p onClick={toggleChatBox} className='jian'>—</p>
                    </div>
                    <div className="chatmain">
                        {messages.map((message) => (
                            <div
                                key={message.id}
                                style={{
                                    textAlign: message.sender === 'user' ? 'right' : 'left',
                                    marginBottom: '10px',
                                }}
                            >
                                <div
                                    style={{
                                        display: 'inline-block',
                                        padding: '5px 10px',
                                        borderRadius: '5px',
                                        backgroundColor: message.sender === 'user' ? '#007bff' : '#fff',
                                        color: message.sender === 'user' ? '#fff' : '#000',
                                    }}
                                >
                                    {message.text}
                                    {message.imageUrl && (
                                        <img
                                            src={message.imageUrl}
                                            alt="uploaded"
                                            style={{ width: '100px', marginLeft: '10px', cursor: 'pointer' }}
                                            onClick={() => handleImageClick(message.imageUrl)} // Handle image click
                                        />
                                    )}
                                </div>
                            </div>
                        ))}
                        <div ref={messagesEndRef} />
                    </div>
                    <div className='chatfooter'>
                        <div className='rengong'></div>
                        <div className='inp'>
                            <input
                                type="text"
                                value={inputValue}
                                onChange={(e) => setInputValue(e.target.value)}
                                placeholder='很高兴为您服务，请描述您的问题'
                            />
                            <button onClick={handleSendMessage}>发送</button>
                            <SmileOutlined onClick={() => setShowEmojiPicker((prev) => !prev)} />
                            {showEmojiPicker && (
                                <div style={{ position: 'absolute', bottom: '50px', right: '10px' }}>
                                    <EmojiPicker onEmojiClick={handleEmojiClick} />
                                </div>
                            )}
                            <input type="file" accept="image/*" onChange={handleImageChange} style={{ marginLeft: '10px' }} />
                            {imagePreview && <img src={imagePreview} alt="preview" style={{ width: '50px', marginLeft: '10px' }} />}
                        </div>
                    </div>
                </div>
            )}
            {previewImageUrl && (
                <Modal visible={true} footer={null} onCancel={handleModalClose}>
                    <img src={previewImageUrl} alt="preview" style={{ width: '100%' }} />
                </Modal>
            )}
        </div>
    );
};

export default Index;
